package com.kyw.androidquicklib.retrofit;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class MyCallBack<T> implements Callback {
    @Override
    public void onResponse(Call call, Response response) {
        if(checkRes(response)){
            Class clzz = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            T t = new Gson().fromJson(json, (Type) clzz);
            onSuccess(t);
        }else {
            onFailed(msg);
        }

    }

    @Override
    public void onFailure(Call call, Throwable t) {

    }
    public abstract void onSuccess(T t);
    public void onFailed(String msg){
        System.out.println("请求错误信息: "+msg);
    }

    String msg;
    String json;
    public boolean checkRes(Response response){
        JSONObject jsonObject = null;
        boolean ret = true;
        try {
            ResponseBody body = (ResponseBody) response.body();
            json = new String(body.bytes());
            jsonObject = new JSONObject(json);
            int value = jsonObject.getInt("flag");
            msg = jsonObject.getString("uiMessage");
            if(value != 200) {//接口请求成功
                System.out.println("请求错误: "+msg);
                ret = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ret = false;
        }
        return ret;
    }
}
